package com.cykj.page07;

import com.cykj.page07.servlet.BaseServlet;
import com.cykj.page07.util.ServletScannerUtils;
import com.cykj.page07.util.ServletUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page05
 * @Author: 阿隆
 * @CreateTime: 2025-10-18 16:19
 * @Description: TODO
 * @Version: 1.0
 */
public class ThreeServeToDynamicServlet {
    public static void main(String[] args) {
        try {
            //创建ServerSocket => 服务器
            ServerSocket serverSocket = new ServerSocket(9090);

            System.out.println("服务端启动端口号为: 9090");

            while (true) {

                //等待客户端连接  阻塞
                Socket socket = serverSocket.accept();

                //读取客户端发送的消息
                InputStream is = socket.getInputStream();

                byte[] bytes = new byte[1024];

                //读取
                int len = is.read(bytes);

                //请求消息
                String request = new String(bytes, 0, len);


                System.out.println(request);


                //解析消息
                MyHttpRequest httpRequest = new MyHttpRequest(request);

                //响应数据
                MyHttpResponse httpResponse = new MyHttpResponse(socket);

                /*
                * 请求模块: 动态资源 /xxxx
                *           静态资源  资源文件路径  pages/index.html
                * */

                System.out.println("请求模块为: " + httpRequest.getRequestModel());

                //通过注解
                BaseServlet baseServlet = ServletScannerUtils.getServletToRequestModel(httpRequest.getRequestModel());

                //有可能是静态资源 404
                if (baseServlet == null) {
                    baseServlet = ServletScannerUtils.getServletToRequestModel("/default");
                }

                baseServlet.requestMethodHandler(httpRequest, httpResponse);


//                String servletName = ServletUtils.getServletNameToKey(httpRequest.getRequestModel());
//
//                //拼接全路径
//                String servletPath = "com.cykj.page07.servlet." + servletName;
//
//                //如果没有获取到serlet的类名  有可能是静态资源
//                if (servletName == null){
//                    servletPath = "com.cykj.page07.servlet.DefaultServlet";
//                }
//
//
//                try {
//                    //获取类对象
//                    Class<?> cls = Class.forName(servletPath);
//
//                    //创建类对象实例
//                    BaseServlet baseServlet = (BaseServlet) cls.newInstance();
//
//                    //调用方法
//                    baseServlet.requestMethodHandler(httpRequest, httpResponse);
//
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }


            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
